package com.mini.game.bus.resource;

import com.mini.common.util.JacksonUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.lang.reflect.Method;
import java.util.List;

public abstract class ResourceDataManager implements IResourceData {
    protected final static Logger logger = LoggerFactory.getLogger(ResourceDataManager.class);
    private final String ROOT_PATH = "data";


    protected <T> List<T> loadResource(String name, Class cls) {
        List<T> retList = null;
        //默认是在jar运行外的路径 兼容下iead运行时的路径
        Method method = null;
        try {
            Method[] methods = cls.getMethods();
            for (Method m : methods) {
                if (m.getName().equals("init")) {
                    method = cls.getMethod("init");
                    break;
                }
            }
        } catch (NoSuchMethodException e) {
            logger.error(e.getMessage(), e);
        }
        File file = new File(ROOT_PATH + File.separator + name);
        try {
            if (!file.exists()) {
//                String path = System.getProperty("user.dir");
//                String path2 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
                file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + ROOT_PATH + File.separator + name);
            }
            String str = FileUtils.readFileToString(file, "utf-8");

            retList = JacksonUtil.stringToList(str, cls);
            if (method != null) {
                for (T t : retList) {
                    if (t != null) {
                        method.invoke(t);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return retList;
    }


    @Override
    public void reloadResource() {
        loadResource();
    }


    @Override
    public int order() {
        return 100;
    }
}
